/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ServerJFrame.java
 *
 * Created on Jun 13, 2012, 2:57:31 PM
 */
package MyGUI;

import MyDataContainer.MyDataString;
import MyDatabaseHandler.DatabaseHandler;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 *
 * @author Welcome
 */
public class ServerJFrame extends javax.swing.JFrame {

    /** Creates new form ServerJFrame */
    public ServerJFrame() {
        initComponents();
        
        myDatabaseList = new ArrayList<DatabaseHandler>();
        ChildThread ct = new ChildThread();		
        ct.start();
                
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldDBName = new javax.swing.JTextField();
        jButtonCreateDatabase = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jPanelCreateTable = new javax.swing.JPanel();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jComboBoxDatabase = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jButtonCreateTable = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jScrollPaneListOfDatabase = new javax.swing.JScrollPane();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Java sql Server");

        jButtonCreateDatabase.setText("Create Database");
        jButtonCreateDatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCreateDatabaseActionPerformed(evt);
            }
        });

        jLabel1.setText("Database Name");

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        jPanelCreateTable.setBorder(javax.swing.BorderFactory.createTitledBorder("Create Table"));

        jTextField2.setText("new_table");

        jLabel3.setText("Table Name");

        jComboBoxDatabase.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxDatabaseItemStateChanged(evt);
            }
        });

        jLabel4.setText("Database");

        jButtonCreateTable.setText("Create Table");

        jButton1.setText("jButton1");

        javax.swing.GroupLayout jPanelCreateTableLayout = new javax.swing.GroupLayout(jPanelCreateTable);
        jPanelCreateTable.setLayout(jPanelCreateTableLayout);
        jPanelCreateTableLayout.setHorizontalGroup(
            jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelCreateTableLayout.createSequentialGroup()
                .addGroup(jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelCreateTableLayout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelCreateTableLayout.createSequentialGroup()
                                .addGroup(jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel4)
                                    .addGroup(jPanelCreateTableLayout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addGap(44, 44, 44)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField2)
                                    .addComponent(jComboBoxDatabase, 0, 121, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addComponent(jButtonCreateTable))
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanelCreateTableLayout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(jButton1)))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        jPanelCreateTableLayout.setVerticalGroup(
            jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelCreateTableLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jComboBoxDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelCreateTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jButtonCreateTable))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jScrollPaneListOfDatabase.setViewportBorder(javax.swing.BorderFactory.createTitledBorder("List of Database"));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPaneListOfDatabase, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(74, 74, 74)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(92, 92, 92)
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jTextFieldDBName, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(jButtonCreateDatabase)))
                    .addComponent(jPanelCreateTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPaneListOfDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonCreateDatabase)
                            .addComponent(jTextFieldDBName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addComponent(jPanelCreateTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(37, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
// TODO add your handling code here:
    
    addDatabaseFromDiskIntoList();
    loadListDatabaseTree();
    //System.out.println(myDatabaseList.size());
}//GEN-LAST:event_formWindowActivated

private void jButtonCreateDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCreateDatabaseActionPerformed
// TODO add your handling code here:
    
    String dbName = jTextFieldDBName.getText();
    if(dbName.equals(""))
    {
        JOptionPane.showMessageDialog(this, "Chua nhap ten database");
        return;
    }
    
    for (int i=0; i<myDatabaseList.size();i++)
    {
        String temp = myDatabaseList.get(i).getDatabaseName();
        if(temp.toLowerCase().equals(dbName.toLowerCase()))
        {
            JOptionPane.showMessageDialog(this, "Trung ten database");
            return;
        }
    }
    
    addDatabaseToList(dbName);
    loadListDatabaseTree();
     
     
}//GEN-LAST:event_jButtonCreateDatabaseActionPerformed

private void jComboBoxDatabaseItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxDatabaseItemStateChanged
// TODO add your handling code here:
    selectedDB = jComboBoxDatabase.getSelectedIndex();
}//GEN-LAST:event_jComboBoxDatabaseItemStateChanged

    /**
     * @param args the command line arguments
     */
        private ArrayList<DatabaseHandler> myDatabaseList;
        private static final String PATH_STRING =".\\src\\server\\Databases\\";
        private int selectedDB = 0;
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ServerJFrame().setVisible(true);            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonCreateDatabase;
    private javax.swing.JButton jButtonCreateTable;
    private javax.swing.JComboBox jComboBoxDatabase;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanelCreateTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPaneListOfDatabase;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextFieldDBName;
    // End of variables declaration//GEN-END:variables

    
    
    private void addDatabaseFromDiskIntoList()
    {
        //Load from disk
        //myDatabaseList.clear();
        File dirFile = new File(PATH_STRING);
        String[] dbList = dirFile.list();
        DatabaseHandler tempDBHandler=null;
        for(int i=0;i<dbList.length;i++)
        {
           
            tempDBHandler = new DatabaseHandler(PATH_STRING+dbList[i]);
            tempDBHandler.ReadDatabase();
            if(myDatabaseList.size()!=0)
            {
                 if(dbList.length !=  myDatabaseList.size())
                    {
                        myDatabaseList.add(tempDBHandler);
                        
                    }
            }
            else
            {
                myDatabaseList.add(tempDBHandler);
            }
      
        }
        
        
    }
    
    public void addDatabaseToList(String dbName)
    {
       
        DatabaseHandler temDatabaseHandler = new DatabaseHandler(PATH_STRING+"Testdb.xml");
        temDatabaseHandler.clearAll();
        temDatabaseHandler.setDatabaseName(dbName);
        temDatabaseHandler.WriteDatabase(PATH_STRING+dbName+".xml");
        myDatabaseList.add(temDatabaseHandler);
    }
    
    private void loadListDatabaseTree()
    {
        //jScrollPaneListOfDatabase.removeAll();
        DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Databases",true);
        for(int i=0; i<myDatabaseList.size();i++)
        {
            
            
            String databaseName = myDatabaseList.get(i).getDatabaseName();
    
            jComboBoxDatabase.addItem(databaseName);
            
            DefaultMutableTreeNode tempNode = new DefaultMutableTreeNode(databaseName,true);
            DefaultMutableTreeNode temp = new DefaultMutableTreeNode("Tables",true);
            tempNode.add(temp);
            String[] tableNames = myDatabaseList.get(i).getTableNames();
            
            for (int j=0; j<tableNames.length;j++)
            {
                DefaultMutableTreeNode temptable = new DefaultMutableTreeNode(tableNames[j],true);
                temp.add(temptable);
                MyDataString columnTitles = myDatabaseList.get(i).getTables().get(j).getColumnTitles();
                MyDataString dataTypeList = myDatabaseList.get(i).getTables().get(j).getDataTypeList();
                
                for (int k =0; k<columnTitles.getSize();k++)
                {
                    DefaultMutableTreeNode tempColumn = new DefaultMutableTreeNode(columnTitles.getAt(k)+" ("+dataTypeList.getAt(k)+")",true);
                    temptable.add(tempColumn);
                }
            }
            
            parent.add(tempNode);
        }
        
        JTree dbTree = new JTree(parent);
            
        jScrollPaneListOfDatabase.setViewportView(dbTree);
    }
    
}
